package com.common.interceptor;


import java.util.ArrayList;

import com.common.exception.AppException;
import com.jfinal.aop.Interceptor;
import com.jfinal.aop.Invocation;
import com.jfinal.core.Controller;
import com.jfinal.kit.Ret;

public class AppExceptionIntercepor implements Interceptor{

	@Override
	public void intercept(Invocation inv) {
		String requestType = inv.getController().getRequest().getHeader("x-requested-with");
		if(requestType!=null&&"XMLHttpRequest".equals(requestType)){//拦截ajax请求
			try {
				inv.invoke();
			} catch (AppException e) {
				Controller controller = inv.getController();
				Ret result = new Ret();
				result.set("_success",false);
				result.set("_message",e.getMessage());
				if(controller.getPara("_type")!=null&&controller.getPara("_type").equals("_refreshDataGrid")){//刷新datagrid的请求，如果不返回这些数据前台会报错
					result.set("total",0);
					result.set("rows",new ArrayList<Object>());
				}
				controller.renderJson(result);
			}
		}else{
			inv.invoke();
		}
	}
}
